from fastapi import APIRouter, Depends, HTTPException, UploadFile, File
from sqlalchemy.orm import Session
from .. import models, schemas
from ..crud import user as user_crud  # 明确导入user模块
from ..database import get_db
from ..deps import get_current_user
from ..utils.files import save_upload_file, AVATAR_DIR
import os
import shutil

router = APIRouter()

@router.get("/me", response_model=schemas.User)
async def read_user_me(current_user: models.User = Depends(get_current_user)):
    """获取当前用户信息"""
    return current_user

@router.put("/me", response_model=schemas.User)
async def update_user_me(
    user_data: schemas.UserUpdate,
    current_user: models.User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """更新当前用户资料"""
    return await user_crud.update_user(db, current_user.id, user_data)

@router.post("/me/profile_image", response_model=schemas.User)
async def update_profile_image(
    profile_image: UploadFile = File(...),
    current_user: models.User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """更新用户头像"""
    # 保存文件
    file_path = f"uploads/profile_images/{current_user.id}_{profile_image.filename}"
    os.makedirs(os.path.dirname(file_path), exist_ok=True)
    
    with open(file_path, "wb+") as file_object:
        shutil.copyfileobj(profile_image.file, file_object)
    
    # 更新数据库中的头像路径
    return user_crud.update_user_image(db, current_user.id, file_path)

@router.get("/{user_id}", response_model=schemas.User)
def read_user(user_id: str, db: Session = Depends(get_db)):
    db_user = user_crud.get_user(db, user_id=user_id)
    if db_user is None:
        raise HTTPException(status_code=404, detail="用户不存在")
    return db_user

@router.put("/{user_id}", response_model=schemas.User)
async def update_user(
    user_id: str,
    user: schemas.UserUpdate,
    current_user: models.User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    if current_user.id != user_id:
        raise HTTPException(status_code=403, detail="只能修改自己的资料")
    return await user_crud.update_user(db, user_id, user)